package network.netty.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import network.netty.Package.TransferPackageWrap;
import network.netty.message.ChatMessage;
import network.netty.message.ChatMessageText;

/**
 * <p>
 * 自定义发送消息handler
 * </p>
 *
 * @author LovelyBigDuck
 * @date 2021/5/30 9:26
 */
public class ClientChatMessageSendHandler extends ChannelInboundHandlerAdapter {
    private Channel channel;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        channel = ctx.channel();
        ChatMessageText message = new ChatMessageText("今天天气下雨了，有点微冷☔️！！！");
        message.setFromIp("67.5.5.4");
        message.setFromUid((long) 123435353);
        for (int i = 0; i < 100; i++) {
            message.setNumber(i);
            sendMessage(message);
        }
    }

    public void sendMessage(ChatMessage message) {
        if (channel != null && channel.isWritable()) {
            TransferPackageWrap transfer = new TransferPackageWrap<>((byte) 1, message);
            channel.writeAndFlush(transfer);
        }
    }
}
